package com.chunuo.configuration.proxy;

import com.chunuo.configuration.factory.TransactionManagerUtils;
import com.chunuo.configuration.interfaces.DataVisit;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

/**
 * aop动态代理  --  事务
 *
 * @author liujiamiao
 * @email 2544296058@qq.com
 * @date 2020-12-23 10:01
 */
public class AOPProxy  {

    public <T> T transactionProxy(Object object){
        Object o = Proxy.newProxyInstance(object.getClass().getClassLoader(), object.getClass().getInterfaces(), new InvocationHandler() {

            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                //toString方法返回动态代理地址
                if (method.getName().equals("toString")) {
                    return this.toString();
                }

                //find、get、query开头的方法不开启事务
                if (method.getName().startsWith("find") || method.getName().startsWith("get") || method.getName().startsWith("query")) {
                    return method.invoke(object, args);
                }
                System.out.println("事务操作~");
                TransactionManagerUtils.startTransaction();

                Object resutl = null;
                try {
                    resutl = method.invoke(object, args);
                    TransactionManagerUtils.commitTransaction();
                } catch (Exception e) {
                    e.printStackTrace();
                    TransactionManagerUtils.rollBackTransaction();
                } finally {
                    TransactionManagerUtils.close();
                }

                return resutl;
            }
        });

        return (T)o;
    }

}
